package core

import "strings"

// Standardize 语法规范化
func Standardize(rows StandardCode) StandardCode {

	counter := 0

	var res StandardCode

	for i, row := range rows {

		if len(row) == 0 {
			continue
		}

		if strings.HasPrefix(row, SentenceTag) {

			res = append(res, row)

			// 结尾处直接加上 {}
			if i >= len(rows)-2 {
				res = append(res, "{")
				res = append(res, "}")
				continue
			}

			// 否则分析下一句
			if strings.TrimSpace(rows[i+1]) != "{" {
				res = append(res, "{")
				res = append(res, "}")
			}

			counter++
			continue
		}

		res = append(res, row)
	}

	return res
}

// FormatCode 标准代码格式化
func (r StandardCode) FormatCode(trees ContextNodes, tab int) FormattedCode {

	var res FormattedCode
	for i := 0; i < len(r); i++ {
		if strings.TrimSpace(r[i]) == "{" && strings.TrimSpace(r[i+1]) == "}" {
			i++
			continue
		}
		prefix := strings.Repeat(" ", tab*trees.FindDepth(i))
		res = append(res, prefix+r[i])
	}

	return FormattedCode(res)
}
